package cn.forkway;

import cn.forkway.domain.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @program: java-learn-mybatis
 * @className: testMyBaties.java
 * @author: River Ray
 * @description: 测试手工编写的mybaties
 * @createTime 2021年10月10日 08:50:00
 */
public class testMyBatis {
    private static SqlSession sqlSession;
    

    @BeforeClass
    public static void init() {
        String config = "mybatis.xml";
        InputStream in = null;
        try {
            in = Resources.getResourceAsStream(config);
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            SqlSessionFactory factory = builder.build(in);
            sqlSession = factory.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Test
    public void testQuery() {
        String sqlId = "cn.forkway.domain.Student" + "." + "selectStudent";
        List<Student> studentList = sqlSession.selectList(sqlId);
        studentList.forEach(System.out::println);
    }

    @Test
    public void testInsert() {
        String sqlId = "cn.forkway.domain.Student" + "." + "insertStudent";
        Student student = new Student();
        student.setName("sed");
        student.setEmail("12312@11.com");
        student.setAge(23);
        int num = sqlSession.insert(sqlId, student);
        System.out.println(num);
        // operation about add delete ...  is involved event;
        sqlSession.commit();
    }

    @Test
    public void testInsert_auto() throws IOException {
        String config = "mybatis.xml";
        InputStream in = Resources.getResourceAsStream(config);
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        sqlSession = factory.openSession(true); // 自动提交事务


        String sqlId = "cn.forkway.domain.Student" + "." + "insertStudent";
        Student student = new Student();
        student.setName("sed");
        student.setEmail("12312@11.com");
        student.setAge(23);
        int num = sqlSession.insert(sqlId, student);
        System.out.println(num);
        // operation about add delete ...  is involved event;
//        sqlSession.commit();
    }

    @AfterClass
    public static void closeSession() {
        sqlSession.close();
    }

}
